package com.ja.openchat.ui.contact.search;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.StringUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.google.gson.JsonObject;
import com.ja.openchat.AppViewModelFactory;
import com.ja.openchat.BR;
import com.ja.openchat.R;
import com.ja.openchat.databinding.ActivityPublicChatSearchBinding;
import com.ja.openchat.ui.chat.ChatActivity;
import com.ja.openchat.ui.contact.ContactDetailActivity;
import com.ja.openchat.ui.contact.ContactDetailSingleActivity;
import com.ja.openchat.viewmodels.PublicChatSearchViewModel;
import com.ja.openchat.views.CustomEditText;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.message.ChatInfo;
import com.zy.openchat.core.model.message.MessageInfo;
import com.zy.openchat.core.model.user.UserInfo;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import me.goldze.mvvmhabit.base.BaseActivity;

/**
 * 公共搜索页面
 */
public class PublicChatSearchActivity extends BaseActivity<ActivityPublicChatSearchBinding, PublicChatSearchViewModel> {
    //分组列表
    //"好友", "公开联系人", "我的群组", "公开群组", "我的频道", "公开频道", "聊天记录"
    private List<SearchSection> sectionList = new ArrayList<>();
    private PublicSearchSectionAdapter publicSearchSectionAdapter;
    //好友
    private List<UserInfo> myContactsList = new ArrayList<>();
    //公开联系人
    private List<UserInfo> publicContactsList = new ArrayList<>();
    private int searchPublicContactsTaskId;
    //我的群组
    private List<ChatInfo> myGroupList = new ArrayList<>();
    //公开群组
    private List<ChatInfo> publicGroupList = new ArrayList<>();
    //我的频道
    private List<ChatInfo> myChannelList = new ArrayList<>();
    //公开频道
    private List<ChatInfo> publicChannelList = new ArrayList<>();
    //聊天记录
    private List<MessageInfo> historyMsgList = new ArrayList<>();
    private int searchHistoryMsgTaskId;


    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_public_chat_search;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }


    @Override
    public PublicChatSearchViewModel initViewModel() {
        //使用自定义的ViewModelFactory来创建ViewModel，如果不重写该方法，则默认会调用LoginViewModel(@NonNull Application application)构造方法
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getApplication());
        return ViewModelProviders.of(this, factory).get(PublicChatSearchViewModel.class);
    }

    @Override
    public void initView() {
        super.initView();
        binding.tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        KeyboardUtils.showSoftInput(binding.etSearch);
        //输入框监听
        binding.etSearch.setOnXTextChangeListener(new CustomEditText.OnXTextChangeListener() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                doSearch(s.toString());
            }
        });
        //
        initList();
    }

    private void initList() {
        //初始化列表
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        binding.recyclerView.setLayoutManager(layoutManager);
        publicSearchSectionAdapter = new PublicSearchSectionAdapter(R.layout.adapter_section_contact_list, sectionList);
        binding.recyclerView.setAdapter(publicSearchSectionAdapter);
        viewModel.setAdapter(publicSearchSectionAdapter);
        //点击事件
        publicSearchSectionAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                if (sectionList != null && sectionList.size() > 0 && position >= 0 && position < sectionList.size()) {
                    Object obj = sectionList.get(position).getObject();
                    if (obj instanceof UserInfo) {
                        UserInfo user = (UserInfo) obj;
                        //跳转个人资料详情
//                        ContactDetailActivity.start(PublicChatSearchActivity.this, user);
                        ContactDetailSingleActivity.start(PublicChatSearchActivity.this, user);
                    }else if(obj instanceof MessageInfo){
                        MessageInfo messageInfo = (MessageInfo)obj;
                        ChatInfo chat = TelegramManager.getTelegramManager().getTgData().chatInfo(messageInfo.chat_id);
                        if(chat!=null){
                            ChatActivity.startActivity(PublicChatSearchActivity.this,chat);
                        }
                    }
                }
            }
        });
    }

    private void doSearch(String keyword) {
        if (searchPublicContactsTaskId > 0) {//结束之前的请求任务
            TelegramManager.getTelegramManager().cancelTask(searchPublicContactsTaskId);
        }
        if (searchHistoryMsgTaskId > 0) {//结束之前的请求任务
            TelegramManager.getTelegramManager().cancelTask(searchHistoryMsgTaskId);
        }
        //清除数据
        myContactsList.clear();
        publicContactsList.clear();
        myGroupList.clear();
        publicGroupList.clear();
        myChannelList.clear();
        publicChannelList.clear();
        historyMsgList.clear();

        //
        if (StringUtils.isEmpty(keyword)) {
            reloadListUI();
            return;
        }

        //搜索好友
        List<UserInfo> list = TelegramManager.getTelegramManager().getTgData().getMyContacts(keyword);
        if (list.size() > 0) {
            myContactsList.addAll(list);
        }

        //搜索公开联系人、公开讨论组、公开频道
        if (keyword.length() >= 5) {
            TelegramManager.getTelegramManager().searchPublicChatsList(this, keyword, new TgResultBlock<List<Long>>() {
                @Override
                public void onResult(Map<String, Object> request, JsonObject response, List<Long> obj) {
                    if (obj != null && obj.size() > 0) {
                        for (long chatId : obj) {
                            ChatInfo chat = TelegramManager.getTelegramManager().getTgData().chatInfo(chatId);
                            if (chat != null) {
                                if (chat.isGroup()) {
                                    //暂不处理
                                } else {
                                    UserInfo user = TelegramManager.getTelegramManager().getTgData().contactInfo(chat.userId());
                                    if (user != null) {
                                        publicContactsList.add(user);
                                    }
                                }
                            }
                        }
                        reloadListUI();
                    }
                }

                @Override
                public void onTimeout(Map<String, Object> request) {

                }
            });
        }
        if(!TextUtils.isEmpty(keyword)){
            TelegramManager.getTelegramManager().searchMessagesList(this, keyword, new TgResultBlock<List<MessageInfo>>() {
                @Override
                public void onResult(Map<String, Object> request, JsonObject response, List<MessageInfo> obj) {
                    if(obj!=null&&obj.size()>0){
                        historyMsgList.addAll(obj);
                    }
                    reloadListUI();
                }

                @Override
                public void onTimeout(Map<String, Object> request) {

                }
            });
        }

        //搜索历史记录

        //重新加载页面
        reloadListUI();
    }

    //"好友", "公开联系人", "我的群组", "公开群组", "我的频道", "公开频道", "聊天记录"
    private void reloadListUI() {
        sectionList.clear();
        if (myContactsList.size() > 0) {//好友
            sectionList.add(new SearchSection(true, new SearchSectionInfo(getString(R.string.friend_text)), SearchSection.SearchSectionType_MyContacts));
            for (UserInfo user : myContactsList) {
                sectionList.add(new SearchSection(false, user, SearchSection.SearchSectionType_MyContacts));
            }
        }
        if (publicContactsList.size() > 0) {//好友
            sectionList.add(new SearchSection(true, new SearchSectionInfo(getString(R.string.public_contact)), SearchSection.SearchSectionType_PublicContacts));
            for (UserInfo user : publicContactsList) {
                sectionList.add(new SearchSection(false, user, SearchSection.SearchSectionType_PublicContacts));
            }
        }
        if (historyMsgList.size() > 0) {//好友
            sectionList.add(new SearchSection(true, new SearchSectionInfo(getString(R.string.chat_record)), SearchSection.SearchSectionType_HisMsgs));
            for (MessageInfo msg : historyMsgList) {
                sectionList.add(new SearchSection(false, msg, SearchSection.SearchSectionType_HisMsgs));
            }
        }
        publicSearchSectionAdapter.notifyDataSetChanged();
    }



}
